/**
 * 
 */
package com.anyuan.wx.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;

import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.anyuan.wx.menu.Menu;
import com.anyuan.wx.pojo.AccessToken;





/**
 * @author liuyanbin
 * @date 2014-2-6
 */
public class CommonUtil {
	
	private static Logger log = LoggerFactory.getLogger(CommonUtil.class);
	// 获取access_token的接口地址（GET） 限200（次/天）
	public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET"; 
	/*
	 * @requestUrl 请求的地址
	 * @requestMethod 请求的方法是post或者get
	 * @outputStr 提交的数据 xml形式
	 */
	public static JSONObject httpRequest(String requestUrl,String requestMethod,String outputStr){
		JSONObject jsonObject = null;
		StringBuffer buffer = new StringBuffer(); 
		try
		{
			//创建TrustManager并使用我们指定的信任管理器初始化
			TrustManager[] tm = {new MyX509TrustManager()};
			SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");  //不要引用错误的包如com.sun.ssl.sslcontext
			sslContext.init(null, tm, new java.security.SecureRandom());
			//从上述sslContext得到sslSocketFactory对象
			SSLSocketFactory ssf = sslContext.getSocketFactory();
			
			URL url = new URL(requestUrl);
			HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
			httpsURLConnection.setSSLSocketFactory(ssf);
			httpsURLConnection.setDoOutput(true);
			httpsURLConnection.setDoInput(true);
			httpsURLConnection.setUseCaches(true);
			//设置请求方式
			httpsURLConnection.setRequestMethod(requestMethod);
			
			if("GET".equalsIgnoreCase(requestMethod))
				httpsURLConnection.connect();
			//当有数据提交时
			if(null != outputStr){
				OutputStream  outputStream = httpsURLConnection.getOutputStream();
				outputStream.write(outputStr.getBytes("UTF-8"));
				outputStream.close();
			}
			//将返回的输入流转为字符串
			InputStream inputStream = httpsURLConnection.getInputStream();
			InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
			
			BufferedReader buff = new BufferedReader(inputStreamReader);
			
			String str = null;
			while((str = buff.readLine())!=null)
			{
				buffer.append(str);
			}
			
			//释放资源
			buff.close();
			inputStreamReader.close();
			inputStream.close();
			inputStream = null;
			
			httpsURLConnection.disconnect();
			jsonObject = JSONObject.fromObject(buffer.toString());			
			
		}catch(ConnectException e){
			log.error("Connection error",e);
		}
		catch(Exception e){
			log.error("http request error{}",e);
		}
		
		return jsonObject;
			
	}
	
	//菜单创建需要
	public static AccessToken getAccessToken(String appid,String appSecret){
		
		AccessToken accessToken = null;
		
		String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appSecret);
		
		JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
		
		if(null != jsonObject)
		try{
			accessToken = new AccessToken();
			accessToken.setToken(jsonObject.getString("access_token"));
			accessToken.setExpireTime(jsonObject.getInt("expires_in"));
			
		}catch (Exception e) {
			accessToken = null;
			log.error("获取access token失败,errcode{},errmessage{}",jsonObject.getInt("errcode"),jsonObject.getString("errmsg"));
			
		}		  
		
		return accessToken;
		
	}
	
	
	
	

}
